<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="年级+专业 " prop="major">
        <el-input
          v-model="queryParams.major"
          placeholder="请输入年级+专业 如“22级计算机”"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="加入时间 " prop="joinTime">
        <el-input
          v-model="queryParams.joinTime"
          placeholder="请输入加入时间 如“2023.10"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="擅长专长" prop="expertise">
        <el-input
          v-model="queryParams.expertise"
          placeholder="请输入擅长专长"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="就职单位" prop="employmentCompany">
        <el-input
          v-model="queryParams.employmentCompany"
          placeholder="请输入就职单位"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入联系电话"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否在站" prop="isOnDuty">
        <el-input
          v-model="queryParams.isOnDuty"
          placeholder="1：在站成员；0：出站成员"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['RDTeam:info:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['RDTeam:info:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['RDTeam:info:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['RDTeam:info:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="Uuid" align="center" prop="memberId" />-->
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="头像" align="center" prop="pictureUrl" >
        <template v-slot="scope">
          <img v-if="scope.row.pictureUrl" :src="scope.row.pictureUrl" class="table-avatar" @error="handleImageError" />
        </template>
      </el-table-column>
      <el-table-column label="年级+专业 如“22级计算机”" align="center" prop="major" />
      <el-table-column label="加入时间 如2023.10" align="center" prop="joinTime" :formatter="formatJoinTime"/>
      <el-table-column label="擅长专长" align="center" prop="expertise" />
      <el-table-column label="就职单位" align="center" prop="employmentCompany" />
      <el-table-column label="联系电话" align="center" prop="phone" />
      <el-table-column label="是否在站" align="center" prop="isOnDuty" :formatter="statusFormatter" />
      <el-table-column label="成长记录" align="center" prop="growthRecord">
        <template v-slot="scope">
          <el-button type="text" @click="handleGrowthRecordClick(scope.row.memberId)">查看成长记录</el-button>
          <el-dialog title="成长记录" :visible.sync="dialogTableVisible">
            <el-table :data="activities">
              <el-table-column type="index" property="date" label="序号" width="150"></el-table-column>
              <el-table-column property="content" label="比赛"></el-table-column>
              <el-table-column property="timestamp" label="时间"></el-table-column>
            </el-table>
          </el-dialog>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['RDTeam:info:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['RDTeam:info:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改研发团队成员展示对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form
        ref="form"
        :model="formData"
        :rules="rules">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="头像" prop="pictureUrl">
          <el-upload
            class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :on-change="handleAvatarChange"
            :before-upload="beforeAvatarUpload">
            <img v-if="formData.pictureUrl" :src="formData.pictureUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="年级+专业" prop="major">
          <el-input v-model="formData.major" placeholder="请输入年级+专业 如“22级计算机”" />
        </el-form-item>
        <el-form-item label="加入时间”，如2023.10" prop="joinTime">
          <el-input v-model="formData.joinTime" placeholder="请输入加入时间 如“2023.10" />
        </el-form-item>
        <el-form-item label="擅长专长" prop="expertise">
          <el-input v-model="formData.expertise" placeholder="请输入擅长专长" />
        </el-form-item>
        <el-form-item label="就职单位" prop="employmentCompany">
          <el-input v-model="formData.employmentCompany" placeholder="请输入就职单位" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="是否在站">
          <el-radio-group v-model="formData.isOnDuty">
            <el-radio :label="0">出站</el-radio>
            <el-radio :label="1">在站</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInfo, getInfo, delInfo, addInfo, updateInfo } from "@/api/team/info";
export default {
  name: "Info",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 研发团队成员展示表格数据
      infoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      avatarList:[],
      dialogTableVisible: false,
      memberDetails: {
        name: '', // 初始化name属性
        pictureUrl: '',
        major: '',
        joinTime: '',
        expertise: '',
        totalScore: '',
        employmentCompany: '',
        phone: '',
        member: [],
        productList: [],
        gameList: []
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        pictureUrl: null,
        major: null,
        joinTime: null,
        expertise: null,
        employmentCompany: null,
        phone: null,
        isOnDuty: null
      },
      // 表单参数
      formData: {},
      // 表单校验
      rules: {}
    };
  },
  computed: {
    activities() {
      // 格式化时间为“年年年年月月”的格式
      const formatTimestamp = (timestamp) => {
        // 如果时间是类似 "2023.10" 的格式（带小数点），先处理为 Date 对象
        let date;
        if (timestamp.includes('.')) {
          const [year, month] = timestamp.split('.');
          date = new Date(`${year}-${month}-01`); // 创建一个类似 "2023-10-01" 的日期
        } else {
          // 如果时间已经是类似 "2023年12月" 这种格式，直接转换
          const yearMonth = timestamp.replace('年', '-').replace('月', '');
          date = new Date(yearMonth); // 创建一个类似 "2023-12" 的日期
        }

        const year = date.getFullYear();
        const month = date.getMonth() + 1; // getMonth() 返回的月份从0开始，所以需要 +1
        return `${year}年${month}月`;
      };


      // 合并 productList 和 gameList，并为每项加上时间戳和内容
      const productActivities = this.memberDetails.productList.map(item => ({
        timestamp: formatTimestamp(item.productTime),
        content: `参加了${item.productName}项目的开发`
      }));

      const gameActivities = this.memberDetails.gameList.map(item => ({
        timestamp: formatTimestamp(item.gameTime),
        content: `在 ${item.gameName} 比赛中获得 ${item.gameResult}`
      }));

      // 合并两个数组并按时间排序
      const activities = [...productActivities, ...gameActivities];
      return activities.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
    },

  },
  mounted() {
    this.getList();
  },
  methods: {
    formatJoinTime(row, column, cellValue, index) {
      // 检查cellValue是否存在，并且是否符合“年.月”的格式
      if (cellValue && cellValue.includes('.')) {
        // 分离年和月
        const [year, month] = cellValue.split('.').map(Number);
        // 格式化为“年+月”的格式
        return `${year}年${month}月`;
      }
      return cellValue; // 如果不符合预期格式，返回原始值
    },
    handleImageError(event) {
      // 设置图片加载失败时的默认图片
      event.target.src = '../../assets/images/avatar.jpg';
    },
    // 查询个人
    async getMemberDetails(id) {
      this.loading = true; // 开始加载
      try {
        const response = await getInfo(id); // 调用 listInfo 方法并等待响应
        this.memberDetails.member = response.data;
        this.memberDetails.productList = response.data.mProductCenterList;
        this.memberDetails.gameList = response.data.mGameRecordList;
      } catch (error) {
        console.error('Error fetching members:', error); // 处理错误
      } finally {
        this.loading = false; // 结束加载
      }
    },
    handleGrowthRecordClick(id) {
      // 获取成员详情并显示对话框
      this.getMemberDetails(id);
      this.dialogTableVisible = true; // 显示对话框
    },
    /** 查询研发团队成员展示列表 */
    getList() {
      this.loading = true;
      listInfo(this.queryParams).then(response => {

        this.infoList = response.rows;
        console.log("infoList--------");
        console.log(this.infoList); // 打印处理后的 infoList
        this.total = response.total;
        this.loading = false;
      });


    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.formData = {
        memberId: null,
        name: null,
        pictureUrl: null,
        major: null,
        joinTime: null,
        expertise: null,
        employmentCompany: null,
        phone: null,
        isOnDuty: null,
        avatarFile: null,

      };
      this.resetForm("formData");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.memberId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加研发团队成员展示";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const memberId = row.memberId || this.ids
      getInfo(memberId).then(response => {
        this.formData = response.data;
        this.open = true;
        this.title = "修改研发团队成员展示";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        console.log("formDta")
        console.log(this.formData)
        console.log(this.formData.memberId)
        // 创建 FormData 对象
        const formData = new FormData();
        // 动态处理 avatarFile
        if (this.formData.avatarFile instanceof File) {
          formData.append('avatarFile', this.formData.avatarFile);
        }
        // 将表单中的其他数据添加到 FormData
        formData.append('memberId',this.formData.memberId)
        formData.append('name', this.formData.name);
        formData.append('major', this.formData.major);
        formData.append('joinTime', this.formData.joinTime);
        formData.append('expertise', this.formData.expertise);
        formData.append('employmentCompany', this.formData.employmentCompany);
        formData.append('phone', this.formData.phone);
        formData.append('pictureUrl',this.formData.pictureUrl)

        if (valid) {
          if (this.formData.memberId != null) {
            updateInfo(this.formData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInfo(this.formData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const memberIds = row.memberId || this.ids;
      this.$modal.confirm('是否确认删除研发团队成员展示编号为"' + memberIds + '"的数据项？').then(function () {
        return delInfo(memberIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('RDTeam/info/export', {
        ...this.queryParams
      }, `info_${new Date().getTime()}.xlsx`)
    },
    //在站出站文字显示
    statusFormatter(row, column) {
      const value = row[column.property];
      return value === 1 ? '在站成员' : '出站成员';
    },
    handleAvatarSuccess(response, file) {
      // 上传成功后的回调
      this.formData.avatarFile= URL.createObjectURL(file.raw);
      this.formData.pictureUrl = response.data.url; // 假设返回的response中有文件的URL
    },
    /** 上传前的处理 */
    beforeAvatarUpload(file) {
        const isImage = file.type.startsWith("image/");
        const isLt80M = file.size / 1024 / 1024 < 80; // 限制文件大小为 80MB

        if (!isImage) {
          this.$message.error("上传的文件必须是图片格式!");
        }

        if (!isLt80M) {
          this.$message.error("上传的图片大小不能超过 80MB!");
        }

        if (this.avatarList.length >= 1) {
          this.$message.error("只允许上传一张图片!");
          return false; // 阻止上传
        }

        return isImage && isLt80M;
      },
    /** 图片变化时的处理函数 */
    handleAvatarChange(file) {
      console.log("file.raw")
    console.log(file.raw)

      // 使用 URL.createObjectURL 来创建本地 URL
      this.formData.pictureUrl = URL.createObjectURL(file.raw); // 获取本地图片 URL
      console.log("formdatapictural",this.formData.pictureUrl)
      this.formData.avatarFile = file.raw; // 保存文件内容
      console.log(this.formData.avatarFile)
    },


  }
};
</script>
<style>
.el-form--inline {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap; /* 允许换行 */
}

.el-form--inline .el-form-item {
  margin-right: 10px; /* 为每个表单项之间添加一些间距 */
  display: flex;
  align-items: center;
}

.el-form--inline .el-form-item__label {
  flex-shrink: 0; /* 防止label在缩小屏幕时被压缩 */
  margin-right: 10px; /* label和输入框之间的间距 */
  white-space: nowrap;
}

.el-form--inline .el-form-item__label {
  width: auto !important; /* 根据实际情况调整宽度 */
  white-space: nowrap;
}

/* 图片上传 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.table-avatar {
  width: 40px; /* 指定图片宽度 */
  height: 40px; /* 指定图片高度 */
  border-radius: 50%; /* 如果需要圆形头像 */
  object-fit: cover; /* 裁剪图片以适应容器 */
}

.el-icon-user-solid {
  font-size: 40px; /* 设置图标大小 */
  color: #c0c4cc; /* 设置图标颜色 */
}
</style>
